package kr.ac.skhu.m.data;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import kr.ac.skhu.m.value.NoticeListValue;

public class IndexBoardData {
	
	private String url;

	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	
	public IndexBoardData() {
	
	}
	public IndexBoardData(String url) {
		this.url = url;
	}
	
	public List<NoticeListValue> getNoticeListValue() throws Exception {
		
		//해당 URL 페이지를 가져온다.
		Source source = new Source(new URL(url));

		//메소드 찾기를 위해 시작부터 끝까지 태그들만 parse 한다 (?)
		source.fullSequentialParse();
		
		/**
		 * 목록 생성
		 */
		List<Element> board_list = source.getAllElementsByClass("left15");
		int board_list_length = board_list.size();
		
		if(board_list_length >= 5){
			board_list_length = 5;
		}
		
		List<NoticeListValue> valueList = new ArrayList<NoticeListValue>();
		String text = "";
		String idx = "";
		String name = "";
		String todayDate = "";
		
		String href = "";
		int start = 0; 
		int end = 0; 

		for(int i=0; i<board_list_length; i++){
			Element element = board_list.get(i).getAllElements(HTMLElementName.A).get(0);
			text = element.getTextExtractor().toString();
			href = element.getAttributeValue("href");

			Element tr = element.getParentElement().getParentElement().getParentElement();	
			name = tr.getChildElements().get(3).getTextExtractor().toString();
			todayDate = tr.getChildElements().get(4).getTextExtractor().toString();
			
			start = href.indexOf("idx=") + 4;
			end = href.indexOf("&");

			idx = href.substring(start, end);

			valueList.add(new NoticeListValue(text, idx, name, todayDate));
		} 
		
		return valueList;
	}
	
}
